package main

import (
	"fmt"
	"github.com/go-cmd/cmd"
	"github.com/rs/zerolog/log"
	"strings"
	"time"
)

func main() {
	// TODO 第一种方案，等命令执行完，获取全部输出信息
	//commod := "ffprobe -v error -show_streams -print_format json /run/media/fan/MyPassport/ffmpeg/workdir/4K-T-ara-Number9.mp4"
	//commod = "ffmpeg -re -i /run/media/fan/MyPassport/ffmpeg/workdir/4K-T-ara-Number9.mp4 -c copy -f segment -segment_format mp4 -segment_time 60 -segment_list_type csv -segment_list /run/media/fan/MyPassport/ffmpeg/workdir/filelist.csv /run/media/fan/MyPassport/ffmpeg/workdir/test_output-%d.mp4"
	commod := "ffmpeg -re -i /data/4K-T-ara-Number9.mp4 -c copy -f segment -segment_format mp4 -segment_time 40 -segment_list_type csv -segment_list /data/filelist.csv /data/aaa/test_output-%d.mp4"
	// Create Cmd, buffered output
	order := strings.Fields(commod)
	envCmd := cmd.NewCmd(order[0], order[1:]...)
	fmt.Println("===================")
	// Run and wait for Cmd to return Status
	status := <-envCmd.Start()
	fmt.Println("==========++++=========")

	// Print each line of STDOUT from Cmd
	for _, line := range status.Stdout {
		log.Debug().Msgf("Stdout:%s", line)
	}
	log.Info().Msgf("==========++++=========")
	for _, line := range status.Stderr {
		log.Debug().Msgf("Stderr:%s", line)
	}
	log.Info().Msgf("==========++++------------=========")
	log.Debug().Msgf("Error:%v", status.Error)
	log.Debug().Msgf("Exit:%v", status.Exit)
	log.Debug().Msgf("Cmd:%v", status.Cmd)
	log.Debug().Msgf("Complete:%v", status.Complete)
	log.Debug().Msgf("PID:%v", status.PID)
	log.Debug().Msgf("StartTs:%v", status.StartTs)
	log.Debug().Msgf("StopTs:%v", status.StopTs)
	log.Debug().Msgf("Runtime:%v", status.Runtime)

	//TODO  这儿是第二种方案，定时从通道获取信息
	// Start a long-running process, capture stdout and stderr
	findCmd := cmd.NewCmd(order[0], order[1:]...)
	statusChan := findCmd.Start() // non-blocking

	ticker := time.NewTicker(2 * time.Second)

	// Print last line of stdout every 2s
	go func() {
		for range ticker.C {
			status := findCmd.Status()
			n := len(status.Stdout)
			fmt.Println(status.Stdout[n-1])
		}
	}()

	// Stop command after 1 hour
	go func() {
		<-time.After(1 * time.Hour)
		findCmd.Stop()
	}()

	// Check if command is done
	select {
	case finalStatus := <-statusChan:
		fmt.Println(finalStatus)
		// done
	default:
		// no, still running
	}

	// Block waiting for command to exit, be stopped, or be killed
	finalStatus := <-statusChan
	fmt.Println(finalStatus)

}
